package com.shijf.ds;

/**
 * @Author shijf
 * @Description //基于数组实现的队列（可持续进出）
 * @Date 15:13 2023/10/26
 **/
public class ArrayQueueOptimize {

    /**
     * 数组存放数据
     */
    public int[] array;
    /**
     * 数组长度
     */
    public int length;
    private int head; //队头
    private int tail; //队尾
    /**
     * 队列当前元素个数
     */
    private int size;

    public ArrayQueueOptimize(int length){
        array = new int[length];
        this.length = length;
        head = 0;
        tail = 0;
        size = 0;
    }

    //入队，
    public boolean adQueue(int value){
        //如果队列满了，即可返回false
        if(size == length){
            //打印队列中有哪些数据
            for(int i=0;i<length;i++){
                System.out.println("队列存在内容:"+array[i]);
            }
            throw new RuntimeException("队列已满，无法入队");
        }

        if(tail >= length){
            tail = 0;
        }

        //将元素放入队尾
        array[tail++] = value;
        size++;
        return true;
    }

    //出队 将队头的元素取出
    public int deQueue(){
        //如果队列为空，则返回-1
        if(size == 0){
            return -1;
        }
        if(tail >= length){
            tail = 0;
        }
        //取出队头的数据
        int value = array[head++];
        //元素个数 减1
        size--;
        return value;
    }
    //获取队列长度里面的元素数量
    public int getQueueSize(){
        return  this.size;
    }

    public static void main(String[] args) {
        ArrayQueueOptimize arrayQueue = new ArrayQueueOptimize(5);
        arrayQueue.adQueue(1);
        arrayQueue.adQueue(2);
        System.out.println(arrayQueue.deQueue());
        arrayQueue.adQueue(3);
        arrayQueue.adQueue(4);
        System.out.println(arrayQueue.deQueue());
        System.out.println(arrayQueue.deQueue());
        arrayQueue.adQueue(5);
        arrayQueue.adQueue(6);
        arrayQueue.adQueue(7);
        arrayQueue.adQueue(8);
        arrayQueue.adQueue(9);
    }
}
